package main.编程题;

/**
 * @author tmh
 * @date 2024/8/1 16:59
 * @description 一个线程打印奇数，一个线程打印偶数，交替打印，顺序输出
 * 利用wait，notify要搭配synchronized使用
 */
public class T线程交替打印奇偶数wait_notify {
    //定义一个共享变量
    private static final Object lock = new Object();
    //定义初始值
    private static int number = 1;
    //定义最大值
    private static int maxNumber = 100;

    public static void main(String[] args) {


        Thread oddThread = new Thread(() -> {
            while (number <= maxNumber) {
                synchronized (lock) {
                    if (number % 2 == 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        //这是奇数的逻辑，所以就直接打印number，然后唤醒另一个线程
                        System.out.println("奇数: " + number);
                        number++;
                        lock.notify();
                    }
                }
            }

        });

        Thread evenThread = new Thread(() -> {
            //这个if判断的就是奇数的逻辑
            while (number <= maxNumber) {
                synchronized (lock) {
                    if (number % 2 != 0) {
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    } else {
                        System.out.println("偶数: " + number);
                        number++;
                        lock.notify();
                    }
                }
            }
        });

        oddThread.start();
        evenThread.start();

    }


}
